package server

import (
	"sieve_admin_server_userpass/pkg/formatStruct"
	"sieve_admin_server_userpass/pkg/util/convert"
	"strconv"
	"strings"
)

func init() {
	BatchRegModTree(
		&BatchModTree{
			Name: "adminMod", Title: "后台权限管理", Order: 1000, Icon: "logo-freebsd-devil",
			Children: []*BatchModTree{
				{
					Obj:   &mod_rolePerm{},
					Name:  "rolePerm",
					Title: "角色权限", Perms: []*Perm{
						{Name: "query", Title: "查询"},
						{Name: "edit", Title: "修改"},
					},
					Order: 1000,
				},
				{
					Obj:   &mod_staticfile{},
					Name:  "staticfile",
					Title: "上传后台文件", Perms: []*Perm{
						{Name: "query", Title: "查询"},
						{Name: "upload", Title: "上传"},
						{Name: "reback", Title: "回滚"},
					},
					Order: 990,
				},
				{
					Obj:   &mod_opLog{},
					Name:  "opLog",
					Title: "操作日志", Perms: []*Perm{
						{Name: "query", Title: "查询"},
					},
					Order: 900,
				},
			},
		},
	)
}

type mod_rolePerm struct{}

func (r *mod_rolePerm) API_query_list(ctx *Context) interface{} {
	List := make(map[string]interface{})
	List["Mods"] = GetModTree(ctx.Uid)
	List["Roles"] = GetRoles()
	return List
}
func (r *mod_rolePerm) API_edit_rolePerm(ctx *Context) interface{} {
	return SetRolePerms(convert.Atoi(ctx.Args.Get("rid")), strings.Split(ctx.Args.Get("perms"), "|"))
}

type mod_opLog struct{}

func (r *mod_opLog) API_query_search(ctx *Context) interface{} {
	List := make(map[string]interface{})
	rows, err := db.Query("SELECT Uid,Name from im_allUser")
	list := []*User{}
	if err != nil {
		return List
	}
	defer rows.Close()
	for rows.Next() {
		info := &User{}
		err := rows.Scan(&info.Uid, &info.Name)
		if err != nil {
			return List
		}
		list = append(list, info)
	}
	List["UserList"] = list
	List["AppUsers"] = GetUsers()
	return List
}

type opLogInfo struct {
	Id         int
	Uid        int
	Path       string
	IP         string
	UA         string
	CreateTime int
}

func (r *mod_opLog) API_query_list(ctx *Context) interface{} {
	filedKeys, filedValue := formatStruct.ParseUrlSelectData([]string{"searchUid", "searchBeginTime", "searchEndTime", "searchPath"}, []string{"Uid", "BeginTime", "EndTime", "Path"}, ctx.Args)
	currentPage, err := strconv.Atoi(ctx.Args.Get("searchPage"))
	if err != nil {
		currentPage = 1
	}
	pageSize, err := strconv.Atoi(ctx.Args.Get("searchPageSize"))
	if err != nil {
		pageSize = 50
	}
	offset := (currentPage - 1) * pageSize
	sql := "SELECT " + formatStruct.ParseStructFields(&opLogInfo{}).ColsToString() + " from `app_op_log`"
	sql2 := "SELECT count(*) from `app_op_log` "
	if len(filedKeys) > 0 {
		sql += " WHERE "
		sql2 += " WHERE "
		for index, filed := range filedKeys {
			if index > 0 {
				sql += " AND "
				sql2 += " AND "
			}
			if filed == "BeginTime" {
				sql += "`CreateTime` >= ?"
				sql2 += "`CreateTime` >= ?"
			} else if filed == "EndTime" {
				sql += "`CreateTime` <= ?"
				sql2 += "`CreateTime` <= ?"
			} else if filed == "Path" {
				sql += filed + " like ?"
				sql2 += filed + " like ?"
				filedValue[index] = "%" + filedValue[index].(string) + "%"
			} else {
				sql += filed + "=?"
				sql2 += filed + "=?"
			}
		}
	}
	sql += " order by Id DESC limit ?,?"
	ret := make(map[string]interface{})
	var (
		TotalCnt int
	)
	db.QueryRow(sql2, filedValue...).Scan(&TotalCnt)

	filedValue = append(filedValue, offset, pageSize)
	rows, err := db.Query(sql, filedValue...)
	if err != nil {
		return err
	}
	defer rows.Close()
	list := []*opLogInfo{}
	for rows.Next() {
		info := &opLogInfo{}
		err := rows.Scan(formatStruct.ParseStructFields(info).GetPtrs()...)
		if err != nil {
			return err
		}
		list = append(list, info)
	}

	ret["List"] = list
	ret["TotalCnt"] = TotalCnt
	return ret
}
